<?php
/**
 * ============================================================================
 * * COPYRIGHT 2016-2019 xhadmin.com , and all rights reserved.
 * * WEBSITE: http://www.xhadmin.com;
 * ----------------------------------------------------------------------------
 * This is not a free software!You have not used for commercial purposes in the
 * premise of the program code to modify and use; and publication does not allow
 * any form of code for any purpose.
 * ============================================================================
 * Author: 寒塘冷月 QQ：274363574
 */
 
 
namespace app\index\service;
use think\exception\ValidateException;
use think\facade\Validate;

class FormExtendService
{
	
	//提交表单数据
	public function saveData($formData){
		$fieldList = db("field")->where('extend_id',$formData['form_id'])->order('sortid asc')->select()->toArray();
		if(!$fieldList){
			throw new ValidateException('模型不存在');
		} 
		$extInfo = db('extend')->where('extend_id',$formData['form_id'])->find();
		
		if(!$extInfo['is_post']){
			throw new ValidateException('禁止投稿');
		}
		foreach($fieldList as $key=>$v){		
			$rule = [];
			if(!empty($v['validate']) || !empty($v['rule'])){
				if(in_array('notEmpty',explode(',',$v['validate']))){
					array_push($rule,'require');
					$msg[$v['field'].'.require'] = $v['name'].'不能为空';
				}

				if(in_array('unique',explode(',',$v['validate']))){
					array_push($rule,'unique:'.$extInfo['table_name']);
					$msg[$v['field'].'.unique'] = $v['name'].'已存在';
				}
				
				if(!empty($v['rule'])){
					$rule['regex'] = html_out($v['rule']);
					$msg[$v['field'].'.regex'] = $v['name'].'格式错误';
				}
				$rules[$v['field']] = $rule;
			}
			
			if($v['type'] == 7){
				$formData[$v['field']] = strtotime($formData[$v['field']]);
			}		
			if($v['type'] == 12){
				$formData[$v['field']] = time();
			}
			if($v['type'] == 20){
				$formData[$v['field']] = ip();
			}
		}
		
		$validate = Validate::rule($rules)->message($msg);	
		if (!$validate->check($formData)) {
			throw new ValidateException($validate->getError());
		}
		
		try{
			db($extInfo['table_name'])->insertGetId($formData);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return true;
		
	}
	
}
